package activity.personal;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.itboye.hutoubenjg.R;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import adapter.repair_adapter.AllSkillsAdapter;
import adapter.repair_adapter.HasAddAdapter;
import base.BaseActivity;
import bean.LuntanForumItemBean;
import presenter.SysTemPresenter;
import presenter.UserPresenter;
import util.utls.ByAlert;
import util.utls.Const;
import util.utls.IsUtilUid;
import util.utls.SPUtils;
import util.volley.ResultEntity;
import widget.DragGrid;
import widget.OtherGridView;

/**
 * 维修
 * Created by itboye on 2016/12/7.
 */

public class ActivityRepair extends BaseActivity implements AdapterView.OnItemClickListener, Observer {
    /**
     * 用户栏目的GRIDVIEW
     */
    private DragGrid userGridView;
    /**
     * 其它栏目的GRIDVIEW
     */
    private OtherGridView otherGridView;
    /**
     * 用户栏目对应的适配器，可以拖动
     */
    private HasAddAdapter userAdapter;
    /**
     * 其它栏目对应的适配器
     */
    private AllSkillsAdapter allSkillsAdapter;
    /**
     * 用户栏目列表
     */
    private LuntanForumItemBean userChannelList = new LuntanForumItemBean();
    /**
     * 是否在移动，由于这边是动画结束后才进行的数据更替，设置这个限制为了避免操作太频繁造成的数据错乱。
     */
    boolean isMove = false;

    private TextView tvTitle;
    private ImageView back;
    SysTemPresenter presenter;
    private ArrayList<LuntanForumItemBean.AllSkills> allSkillsArrayList;
    private ArrayList<LuntanForumItemBean.UserSkills> userSkillsArrayList;
    String uid="";
    Button btnOrder;
    UserPresenter userPresenter;
    public ActivityRepair() {
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_repair);
        tvTitle.setText("添加维修技能");
        userPresenter=new UserPresenter(this);
        initView();
        initData();
        uid= SPUtils.get(this,null, Const.ID,"")+"";
        presenter = new SysTemPresenter(this);
        presenter.onGetJineng(uid);
    }

    @Override
    protected void onInit() {

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.btnOrder://提交技能

                StringBuffer skillIds=new StringBuffer();
                if (userSkillsArrayList!=null) {
                    for (LuntanForumItemBean.UserSkills userSkills : userSkillsArrayList) {
                        skillIds.append(userSkills.getId()+",");
                    }
                }
                if (skillIds.length()<=0) {
                    ByAlert.alert("技能参数不正确哦!");
                }else {
                    showProgressDialog("请求提交中,请稍后",false);
                    userPresenter.jigongRenZheng(uid, skillIds.toString().substring(0, skillIds.length() - 1));
                }
                break;
        }

    }

    /**
     * 初始化数据
     */
    private void initData() {
        //设置GRIDVIEW的ITEM的点击监听
        otherGridView.setOnItemClickListener(this);
        userGridView.setOnItemClickListener(this);
    }

    /**
     * 初始化布局
     */
    private void initView() {
        userGridView = (DragGrid) findViewById(R.id.userGridView);
        otherGridView = (OtherGridView) findViewById(R.id.otherGridView);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**
     * GRIDVIEW对应的ITEM点击监听接口
     */
    ImageView moveImageView = null;

    @Override
    public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
        //如果点击的时候，之前动画还没结束，那么就让点击事件无效
        if (isMove) {
            return;
        }

        switch (parent.getId()) {
            case R.id.userGridView:
                //position为 0，1 的不可以进行任何操作
//                if (position != 0 && position != 1) {
                if (userSkillsArrayList.size()<=1) {
                    ByAlert.alert("至少得保留一项技能");
                    return;
                }
                final LuntanForumItemBean.UserSkills channelUser = ((HasAddAdapter) parent.getAdapter()).getItem(position);//获取点击的频道内容
//添加到最后一个
                if (isAdded(channelUser.getName(),true)) {
                    ByAlert.alert("该技能已经移除");
                    userSkillsArrayList.remove(position);

                    if (allSkillsAdapter.isVisible()) {

                    }else {
                        allSkillsAdapter.setVisible(true);
                    }
                    updateGridView();
                    return;
                }
                moveImageView = getView(view);
                if (moveImageView != null) {
                    TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                    final int[] startLocation = new int[2];
                    newTextView.getLocationInWindow(startLocation);

                    allSkillsAdapter.setVisible(false);

                    LuntanForumItemBean.AllSkills userBean = new LuntanForumItemBean.AllSkills();
                    userBean.setName(channelUser.getName());
                    userBean.setCode(channelUser.getCode());
                    userBean.setId(channelUser.getId());

                    allSkillsArrayList.add(userBean);
                    userSkillsArrayList.remove(position);
                    updateGridView();
//                    new Handler().postDelayed(new Runnable() {
//                        public void run() {
//                            try {
//                                int[] endLocation = new int[2];
//                                //获取终点的坐标
//                                otherGridView.getChildAt(otherGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
//
//                                MoveAnim(moveImageView, startLocation, endLocation, channelUser, otherGridView);
//                            } catch (Exception localException) {
//
//                            }
//                        }
//                    }, 50L);
                }
                break;
            case R.id.otherGridView:
                final LuntanForumItemBean.AllSkills channel = ((AllSkillsAdapter) parent.getAdapter()).getItem(position);
                if (isAdded(channel.getName(),false)) {
                   ByAlert.alert("技能已经添加,不能重复哦");
                    return;
                }
                moveImageView = getView(view);
                if (moveImageView != null) {
                    TextView newTextView = (TextView) view.findViewById(R.id.text_item);
                    final int[] startLocation = new int[2];
                    newTextView.getLocationInWindow(startLocation);

                    userAdapter.setVisible(false);
                    //添加到最后一个
                    LuntanForumItemBean.UserSkills allBean=new LuntanForumItemBean.UserSkills();
                    allBean.setId(channel.getId());
                    allBean.setName(channel.getName());
                    allBean.setCode(channel.getCode());

                    userSkillsArrayList.add(allBean);
                    allSkillsArrayList.remove(position);
                    updateGridView();
//                    new Handler().postDelayed(new Runnable() {
//                        public void run() {
//                            try {
//                                int[] endLocation = new int[2];
//                                //获取终点的坐标
//                                userGridView.getChildAt(userGridView.getLastVisiblePosition()).getLocationInWindow(endLocation);
//                                MoveAnims(moveImageView, startLocation, endLocation, channel, userGridView);
//                            } catch (Exception localException) {
//                            }
//                        }
//                    }, 50L);
                }
                break;
            default:
                break;
        }
    }

    public boolean isAdded(String hasSkilled,boolean isAllClick) {

        boolean isAdded = false;
        if (!isAllClick) {
            if (userSkillsArrayList != null) {
                for (int i = 0; i < userSkillsArrayList.size(); i++) {
                    if (hasSkilled.equals(userSkillsArrayList.get(i).getName())) {
                        isAdded = true;
                        break;
                    } else {
                        isAdded = false;
                    }
                }
            } else {
                isAdded = true;
                return isAdded;
            }
        }else{
            if (allSkillsArrayList != null) {
                for (int i = 0; i < allSkillsArrayList.size(); i++) {
                    if (hasSkilled.equals(allSkillsArrayList.get(i).getName())) {
                        isAdded = true;
                        break;
                    }
                }
            } else {
                isAdded = false;
                return isAdded;
            }
        }


        return isAdded;
    }

    /**
     * 点击ITEM移动动画
     *
     * @param moveView
     * @param startLocation
     * @param endLocation
     * @param moveChannel
     * @param clickGridView
     */
    private void MoveAnim(View moveView, int[] startLocation, int[] endLocation, final LuntanForumItemBean.UserSkills moveChannel,
                          final GridView clickGridView) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    allSkillsAdapter.setVisible(true);
                    allSkillsAdapter.notifyDataSetChanged();
                    userAdapter.notifyDataSetChanged();
                } else {
                    userAdapter.setVisible(true);
                    allSkillsAdapter.notifyDataSetChanged();
                    userAdapter.notifyDataSetChanged();
                }
                isMove = false;
            }
        });
    }

    private void MoveAnims(View moveView, int[] startLocation, int[] endLocation, final LuntanForumItemBean.AllSkills moveChannel,
                           final GridView clickGridView) {
        int[] initLocation = new int[2];
        //获取传递过来的VIEW的坐标
        moveView.getLocationInWindow(initLocation);
        //得到要移动的VIEW,并放入对应的容器中
        final ViewGroup moveViewGroup = getMoveViewGroup();
        final View mMoveView = getMoveView(moveViewGroup, moveView, initLocation);
        //创建移动动画
        TranslateAnimation moveAnimation = new TranslateAnimation(
                startLocation[0], endLocation[0], startLocation[1],
                endLocation[1]);
        moveAnimation.setDuration(300L);//动画时间
        //动画配置
        AnimationSet moveAnimationSet = new AnimationSet(true);
        moveAnimationSet.setFillAfter(false);//动画效果执行完毕后，View对象不保留在终止的位置
        moveAnimationSet.addAnimation(moveAnimation);
        mMoveView.startAnimation(moveAnimationSet);
        moveAnimationSet.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation animation) {
                isMove = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                moveViewGroup.removeView(mMoveView);
                // instanceof 方法判断2边实例是不是一样，判断点击的是DragGrid还是OtherGridView
                if (clickGridView instanceof DragGrid) {
                    allSkillsAdapter.setVisible(true);
                    updateGridView();
                } else {
                    userAdapter.setVisible(true);
                    updateGridView();
                }
                isMove = false;
            }
        });
    }

    /**
     * 获取移动的VIEW，放入对应ViewGroup布局容器
     *
     * @param viewGroup
     * @param view
     * @param initLocation
     * @return
     */
    private View getMoveView(ViewGroup viewGroup, View view, int[] initLocation) {
        int x = initLocation[0];
        int y = initLocation[1];
        viewGroup.addView(view);
        LinearLayout.LayoutParams mLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mLayoutParams.leftMargin = x;
        mLayoutParams.topMargin = y;
        view.setLayoutParams(mLayoutParams);
        return view;
    }

    /**
     * 创建移动的ITEM对应的ViewGroup布局容器
     */
    private ViewGroup getMoveViewGroup() {
        ViewGroup moveViewGroup = (ViewGroup) getWindow().getDecorView();
        LinearLayout moveLinearLayout = new LinearLayout(this);
        moveLinearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
        moveViewGroup.addView(moveLinearLayout);
        return moveLinearLayout;
    }

    /**
     * 获取点击的Item的对应View，
     *
     * @param view
     * @return
     */
    private ImageView getView(View view) {
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(true);
        Bitmap cache = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);
        ImageView iv = new ImageView(this);
        iv.setImageBitmap(cache);
        return iv;
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            IsUtilUid.tianjia(entity);
            if (entity.getEventType() == presenter.GetJineng_success) {
                userChannelList = (LuntanForumItemBean) entity.getData();

                allSkillsArrayList = new ArrayList<>();
                allSkillsArrayList = userChannelList.getAll_skills();

                userSkillsArrayList = new ArrayList<>();
                userSkillsArrayList = userChannelList.getUser_skills();

                //从所有技能中移除掉已经添加了的
                if (allSkillsArrayList!=null) {
                    for (int i = 0; i < userSkillsArrayList.size(); i++) {
                        for (int i1 = 0; i1 < allSkillsArrayList.size(); i1++) {
                           if(userSkillsArrayList.get(i).getName().equals(allSkillsArrayList.get(i1).getName())){
                               allSkillsArrayList.remove(i1);
                                break;
                            }
                        }
                    }
                }
                updateGridView();
            }else if(entity.getEventType() == presenter.GetJineng_fail){

            }else if(entity.getEventType() == UserPresenter.jg_success){
                ByAlert.alert(entity.getData());
                finish();
            }else if(entity.getEventType() == UserPresenter.jg_fail){
                ByAlert.alert(entity.getData());
            }
        }

        try {
            closeProgressDialog();
        }catch (Exception e){

        }
    }

    void updateGridView(){
        userAdapter = new HasAddAdapter(this, userSkillsArrayList);
        userGridView.setAdapter(userAdapter);
        allSkillsAdapter = new AllSkillsAdapter(this,allSkillsArrayList );
        otherGridView.setAdapter(this.allSkillsAdapter);
    }
}
